import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:mall/components/image_network.dart';
import 'package:mall/components/scan_register_container.dart';
import 'package:mall/constants.dart';
import 'package:mall/core/models/store_index.dart';
import 'package:mall/core/models/store_index_req.dart';
import 'package:mall/core/providers/app_model.dart';
import 'package:mall/core/services/new_api.dart';
import 'package:mall/screens/home/home_search_screen.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../theme.dart';
import 'components/home_banner.dart';
import 'components/home_floor.dart';
import 'components/home_group.dart';
import 'components/home_navigator.dart';
import 'components/home_news.dart';
import 'components/home_rush.dart';
import 'components/home_store.dart';

/// 首页
class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  String _error; // 店铺错误信息
  StoreIndex _storeIndex; // 店铺

  @override
  void initState() {
    super.initState();
    _fetchStoreIndex();
  }

  @override
  Widget build(BuildContext context) {
    return _error == null && _storeIndex == null
        ? Scaffold(
            body: Center(
              child: CircularProgressIndicator(),
            ),
          )
        : _storeIndex == null
            ? Scaffold(
                body: Center(
                  child: Text("$_error"),
                ),
              )
            : Scaffold(
                appBar: buildAppBar(),
                body: buildBody(),
              );
  }

  AppBar buildAppBar() {
    return AppBar(
      leading: Padding(
        padding: EdgeInsets.all(8.w),
        // 店铺logo
        child: ImageNetwork(url: "${_storeIndex.store?.logoUrl}", width: 30.w, height: 30.w),
      ),
      // foke搜索
      title: GestureDetector(
        onTap: _onTapSearch,
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 8.w),
          height: 25.w,
          decoration: BoxDecoration(
            border: Border.all(color: kLineColor),
            borderRadius: BorderRadius.circular(12.5.w),
          ),
          child: Row(
            children: [
              Icon(Icons.search),
            ],
          ),
        ),
      ),
      titleSpacing: 0,
      actions: [
        // 扫码注册
        ScanRegisterContainer(
          child: IconButton(
            icon: ImageIcon(AssetImage("assets/icons/qrcode_scanner.png")),
            onPressed: null,
          ),
        ),
      ],
    );
  }

  /// 点击搜索
  void _onTapSearch() {
    Navigator.of(context).pushNamed(HomeSearchScreen.routeName, arguments: HomeSearchScreenArgs());
  }

  SingleChildScrollView buildBody() {
    return SingleChildScrollView(
      child: Column(
        children: [
          // 轮播
          if (_storeIndex.bannerList.isNotEmpty) HomeBanner(banner: _storeIndex.bannerList),
          SizedBox(height: 12.w),
          // 导航
          HomeNavigator(navigator: _storeIndex.navigator),
          SizedBox(height: 12.w),
          // 新闻
          if (_storeIndex.newsList.isNotEmpty) HomeNews(news: _storeIndex.newsList),
          SizedBox(height: 12.w),
          // 团购
          HomeGroup(group: _storeIndex.pinGouList, onEnd: _fetchStoreIndex),
          SizedBox(height: 8.w),
          // 抢购
          HomeRush(rush: _storeIndex.qiangGouList),
          SizedBox(height: 8.w),
          // 店铺
          HomeStore(store: _storeIndex.recommendStoreList),
          SizedBox(height: 8.w),
          // 楼层
          HomeFloor(floor: _storeIndex.floorList),
          SizedBox(height: 8.w),
        ],
      ),
    );
  }

  /// 拉取首页数据
  void _fetchStoreIndex() async {
    final api = context.read<NewApi>();
    final appModel = context.read<AppModel>();
    try {
      // 店铺信息
      final req = StoreIndexReq(
        clientId: clientId,
        dataTypes: ['ALL'],
        storeId: appModel.bindingStoreId,
      );
      final storeIndex = await api.storeIndex(req);
      if (!mounted) {
        return;
      }
      setState(() {
        _storeIndex = storeIndex;
      });
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      setState(() {
        _error = e.message;
      });
    }
  }
}
